<?php

namespace app\bapi\controller;

use app\facade\Redis;
use app\models\{Business, BussinessLog, Order, PlatClass, Goods, GoodsSpec, OrderGoods, Withdraw, Bank};
use EasyWeChat\Factory;
use think\Validate;
use oss\Oss;
use think\Db;

class User extends Base
{
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '手机号不能为空',
            'password.require' => '登陆密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Business();
        //判断用户是否已经注册
        $user = $model->where('account', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '商户不存在');
        }
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '商户密码错误');
        }
        $token = 'buser_' . md5(time() . $user['id']);
        Redis::setex($token, 5 * 86400, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function info()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $arr = [];
            foreach ($data as $key => $datas) {
                if ($datas == "0") {
                    $arr[$key] = (float)$datas;
                } elseif (!empty($datas)) {
                    $arr[$key] = $datas;
                }
            }
            if (!empty($arr['title']) && mb_strlen($arr['title']) < 5) {
                $this->result([], 1, '标题长度过低');
            }
            if (!empty($arr['password'])) {
                $arr['password'] = md5(md5($arr['password']));
            }
            if (!empty($arr['fwtime'])) {
                $fwtime = explode('-', $arr['fwtime']);
                if (count($fwtime) != 2) {
                    return json(['code' => 1, 'data' => [], 'msg' => '时间格式错误']);
                }
                if (strtotime($fwtime[0]) > strtotime($fwtime[1])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '时间范围错误']);
                }
            }
            if (!empty($arr['status']) && ($arr['status'] != 1 && $arr['status'] != 2)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家状态设置错误']);
            }
            if (!empty($arr['title'])) {
                $shop = (new Business())->where('title', $arr['title'])->find();
                if (!empty($shop) && $shop['id'] != $this->request->buser_id) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺名已被使用']);
                }
            }
            $res = (new Business())->allowfield(['title', 'zt', 'descs', 'password', 'fwtime', 'mobile', 'status', 'sendmoney', 'sendkm', 'sendm', 'lat', 'lon', 'getaddress', 'address', 'province', 'city', 'area'])->save($arr, ['id' => $this->request->buser_id]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $user = $this->request->buser;
            unset($user['wopenid']);
            unset($user['openid']);
            unset($user['created']);
            unset($user['password']);
            unset($user['remark']);
            $this->result($user, 0, '获取成功');
        }
    }

    public function getdata()
    {
        //查询所有订单
        $lists = (new Order())->where(['businessid' => $this->request->buser_id, 'status' => [2, 3, 4]])->select();
        $result = [
            'total' => 0, //订单总额
            'all' => 0, //订单总量
            'todaytotal' => 0, //今日总额
            'todayall' => 0 //今日总量
        ];
        foreach ($lists as $list) {
            $result['total'] += $list['ptotal'];
            $result['all'] += 1;
            if (strtotime($list['created']) >= strtotime(date('Y-m-d'))) {
                $result['todaytotal'] += $list['ptotal'];
                $result['todayall'] += 1;
            }
        }
        //精度
        $result = [
            'total' => floor($result['total'] * 100) / 100, //订单总额
            'all' =>  floor($result['all'] * 100) / 100, //订单总量
            'todaytotal' =>  floor($result['todaytotal'] * 100) / 100, //今日总额
            'todayall' =>  floor($result['todayall'] * 100) / 100 //今日总量
        ];
        $this->result($result, 0, '获取成功');
    }

    public function getmonthdata()
    {
        $date = $this->request->get('date');
        $date = empty($date) ? date('Y-m') : $date;
        $times = strtotime($date);
        $start = date('Y-m-01', $times);
        $end = date('Y-m-t', $times);
        //查询所有订单
        $lists = (new Order())->where(['businessid' => $this->request->buser_id])
            ->whereBetweenTime('created', $start, $end)
            ->select();
        $result = [
            'mtotal' => 0, //订单月总额
            'mall' => 0, //订单月总量
            'cacel' => 0, //月取消
            'shorder' => 0, //月售后
            'finish' => 0 //月结束
        ];
        foreach ($lists as $list) {
            if (in_array($list['status'], [2, 3, 4])) {
                $result['mtotal']  += $list['ptotal'];
                $result['mall']  += 1;
            }
            if (in_array($list['status'], [5])) {
                $result['cacel']  += 1;
            }
            if (in_array($list['shouhou'], [2])) {
                $result['shorder']  += 1;
            }
            if (in_array($list['status'], [4])) {
                $result['finish']  += 1;
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function cate()
    {
        $list = (new PlatClass())->where(['isshow' => 1])->order('sort desc')->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function goodlist()
    {
        $model = new Goods();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        $results = $results->where('businessid', $this->request->buser_id);
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['isSale'])) {
            $results = $results->where('isSale', $data['isSale']);
        }
        $results = $results->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true) ?? [];
            $result['goodspec'] = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $result['id']])->order('is_default desc')->select();
        }
        $this->result($results, 0, '获取成功');
    }

    public function good_status()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => '商家ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['isdel']) && $data['isdel'] != 2) {
                $this->result([], 1, '参数错误');
            }
            if (!empty($data['isSale']) && $data['isSale'] != 2 && $data['isSale'] != 1) {
                $this->result([], 1, '参数错误');
            }
            $model = new Goods();
            $goods = $model->where(['businessid' => $this->request->buser_id, 'isdel' => 1, 'id' => $data['id']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品不存在');
            }
            $isSale = !empty($data['isSale']) ? $data['isSale'] : $goods['isSale'];
            $isdel = !empty($data['isdel']) ? $data['isdel'] : $goods['isdel'];
            $res = $model->where('id', $goods['id'])->update(['isSale' => $isSale, 'isdel' => $isdel]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }

    public function uploads()
    {
        if (empty($_FILES['file'])) {
            $this->result([], 1, '参数错误');
        }
        $file = $_FILES['file'];
        $oss = new Oss();
        $oss->setUploadType('ram');
        $url = $oss->uploadPostFile($file, 'lxc/' . date('Y-m-d'));
        $this->result($url, 0, '操作成功');
    }

    public function goods_edit()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'title' => 'require',
            'images' => 'require',
            'classid' => 'require',
            'recomm' => 'require|in:1,2',
            'isnew' => 'require|in:1,2',
            'isSale' => 'require|in:1,2',
            'descs' => 'require',
            'goodsDesc' => 'require',
            'spec' => 'require',
        ], [
            'title.require' => '商品名称不能为空',
            'images.require' => '商品名称不能为空',
            'classid.require' => '商品分类不能为空',
            'recomm.require' => '推荐类型不能为空',
            'recomm.in' => '推荐类型不正确',
            'isnew.require' => '新品类型不能为空',
            'isnew.in' => '新品类型不正确',
            'isSale.require' => '上架类型不能为空',
            'isSale.in' => '上架类型不正确',
            'descs.require' => '商品简述不能为空',
            'goodsDesc.require' => '商品详情不能为空',
            'spec.require' => '商品规格不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $images = json_decode($data['images'], true) ?? [];
        if (count($images) <= 0) {
            $this->result([], 1, '商品图片数据错误，请重试');
        }
        $spec = json_decode($data['spec'], true) ?? [];
        if (count($spec) <= 0) {
            $this->result([], 1, '商品规格数据错误，请重试');
        }
        if (!empty($data['id'])) {
            $model = new Goods();
            $goods = $model->where(['businessid' => $this->request->buser_id, 'isdel' => 1, 'id' => $data['id']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品不存在或已删除');
            }
        }
        $data['businessid'] = $this->request->buser_id;
        Db::startTrans();
        try {
            if (!empty($data['id'])) {
                (new Goods())->allowfield(true)->save(['id' => $data['id']], $data);
                foreach ($spec as $specs) {
                    if (!empty($specs['id'])) {
                        (new GoodsSpec())->where(['goodid' => $data['id'], 'id' => $specs['id']])->update($specs);
                    } else {
                        $specs['businessid'] = $this->request->buser_id;
                        $specs['goodid'] =  $data['id'];
                        (new GoodsSpec())->insert($specs);
                    }
                }
            } else {
                $goodsid = (new Goods())->strict(false)->insertGetid($data);
                foreach ($spec as $specs) {
                    if (!empty($specs['id']) && !empty($data['id'])) {
                        (new GoodsSpec())->where(['goodid' => $data['id'], 'id' => $specs['id']])->update($specs);
                    } else {
                        if (!empty($specs['id'])) {
                            unset($specs['id']);
                        }
                        $specs['businessid'] = $this->request->buser_id;
                        $specs['goodid'] =  $goodsid;
                        (new GoodsSpec())->strict(false)->insert($specs);
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function goodsspec_edit()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'specid' => 'require'
        ], [
            'id.require' => '商品ID不能为空',
            'specid.require' => '商品规格ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new GoodsSpec();
        $spec = $model->where(['businessid' => $this->request->buser_id, "goodid" => $data['id'], 'isdel' => 1, 'id' => $data['specid']])->find();
        if (empty($spec)) {
            $this->result([], 1, "规格信息不存在");
        }
        $res = $model->where('id', $spec['id'])->update(['isdel' => 2]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    public function orderlist()
    {
        $title = $this->request->get('title', '');
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc')->where(['businessid' => $this->request->buser_id, 'status' => [2, 3, 4, 5]]);
        if (!empty($title)) {
            $list = $list->where('code|ordersn|name|mobile', 'like', '%' . $title . '%');
        }
        if (!empty($status)) {
            switch ($status) {
                case '2':
                    $list = $list->where('status', $status)->where('shouhou', 1);
                    break;
                case '3':
                    $list = $list->where('status', $status)->where('shouhou', 1);
                    break;
                case '4':
                    $list = $list->where('status', $status)->where('shouhou', 1);
                    break;
                case '99':
                    $list = $list->where('shouhou', 2);
                    break;
                default:
                    break;
            }
        }
        $list = $list->field('id,type,code,name,mobile,province,city,area,getaddress,address,status,lat,lon,ordersn,remark,total,text,tuikuan,created')
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
            foreach ($ordergoods as $goods) {
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '操作成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $order = (new Order())->order('id desc')
            ->where(['businessid' => $this->request->buser_id, 'id' => $id])
            ->field('id,type,code,name,sendm,mobile,province,city,area,getaddress,address,status,lat,lon,ordersn,remark,total,text,tuikuan,created')
            ->find();
        $ordergoods = (new OrderGoods())->where(['ordersn' => $order['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
        foreach ($ordergoods as $goods) {
            $goods['images'] = json_decode($goods['images'] ?? '', true);
        }
        $order['goods'] = $ordergoods;
        $order['status_text'] = $order->status_text;
        $this->result($order, 0, '操作成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        if (!empty($data['code'])) {
            //查询订单
            $order = (new Order())->order('id desc')
                ->where(['businessid' => $this->request->buser_id, 'code' => $data['code'], 'type' => 2])
                ->find();
            if (!empty($order)) {
                $this->result([], 1, '取货码错误');
            }
            if ($order['status'] != 2 && $order['status'] != 3) {
                $this->result([], 1, '订单已取货或已取消');
            }
            $res = (new Order())->where('id', $order['id'])->update(['status' => 4]);
            if ($res) {
                $this->result(
                    [],
                    0,
                    '操作成功'
                );
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            if (empty($data['id']) && empty($data['status'])) {
                $this->result([], 1, '参数缺失');
            }
            $order = (new Order())->where('id', $data['id'])->where('businessid', $this->request->buser_id)->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] == 4 || $order['status'] == 5) {
                $this->result([], 1, '订单已完成或取消，无法继续操作');
            }
            switch ($data['status']) {
                case '3':
                    if ($order['status'] != 2) {
                        $this->result([], 1, '订单状态不可接单并配送');
                    }
                    $res = (new Order())->where('id', $data['id'])->update(['status' => 3, 'fwtimes' => date('Y-m-d H:i:s')]);
                    if ($res) {
                        $this->result([], 0, '操作成功');
                    }
                    break;
                    //完成订单
                case '4':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        $this->result([], 1, '订单状态不可完成');
                    }
                    $res = (new Order())->where('id', $data['id'])->update(['status' => 4, 'tuikuan' => 0, 'finishtimes' => date('Y-m-d H:i:s')]);
                    if ($res) {
                        $this->result([], 0, '操作成功');
                    }
                    break;
                    //取消订单
                case '5':
                    //未支付订单直接取消
                    if ($order['status'] == 1) {
                        $res = (new Order())->where('id', $data['id'])->update(['status' => 5, 'caceltimes' => date('Y-m-d H:i:s')]);
                        if ($res) {
                            $this->result([], 0, '操作成功');
                        }
                    }
                    //已支付订单递交平台处理退款等操作
                    if ($order['status'] == 2 || $order['status'] == 3) {
                        $res = (new Order())->where('id', $data['id'])->update(['tuikuan' => 2, 'text' => $order['text'] . '|商家已取消订单']);
                        if ($res) {
                            $this->result([], 0, '操作成功,等待平台退款中');
                        }
                    }
                default:
                    $this->result([], 1, '状态出错');
                    break;
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }

    public function getmoneylog()
    {
        $model = new BussinessLog();
        $results = $model->field('id,money,created,info')->order('id desc')->where('user_id', $this->request->buser_id);
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        $this->result($results, 0, '操作成功');
    }

    public function withdraw()
    {
        $list = (new Withdraw())->where('user_id', $this->request->buser_id)->paginate(10, false, ['query' => $this->request]);
        $this->result($list, 0, '操作成功');
    }
}
